package com.gz.logistics.app;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gz.logistics.R;
import com.gz.logistics.library.IAuthor;
import com.gz.logistics.library.IOrder;
import com.gz.logistics.library.listener.GetQueryorderDetailListener;
import com.gz.logistics.library.listener.SingleOrderDeliveryStatusChangeListener;
import com.gz.logistics.library.pojo.OrderDetail;
import com.gz.logistics.library.pojo.ProductInfo;
import com.gz.logistics.library.pojo.UserInfo;
import com.gz.logistics.library.util.Constants;
import com.gz.logistics.library.util.PreferenceModel;
import com.gz.logistics.library.util.Tools;
import com.gz.logistics.util.ToastUtils;
import com.gz.logistics.widget.LoadingCover;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.List;

/**
 * 查询订单详情
 */
public class OrderDetailActivity extends Activity implements View.OnClickListener,LoadingCover.OnLoadingCoverRefreshListener {
    private static String TAG = OrderDetailActivity.class.getSimpleName();
    private OrderDetail orderdetail;//需要显示的订单
    //private ImageView iv_action_back;
    private TextView tv_actionbar_title;
    private TextView tv_actionbar_deliveryName;
    private TextView tv_order_number;
    private TextView tv_create_time;
    private TextView tv_receiver_name;
    private TextView tv_receiver_phone;
    private TextView tv_receiver_address;
    private TextView tv_shimoney;
    private TextView tv_receiver_cpucbt; //提货方式
    private TextView tv_pay_type;  // 支付方式
    private TextView tv_money;  // 应收金额
    private TextView tv_notes;  // 备注

    private LinearLayout productList;
    private TextView tv_order_price;
    private TextView tv_logistic_status;
    public static TextView tv_delivery_status;
    public static Button btn_delivery_confirm;
    private LoadingCover mloadCover;
    private OrderDetailListener listener;

    private UserInfo userInfo;
    private String order_sn = "";
    private String status;


    private boolean isChaged = false;// 标记该订单的转状态是否改变，如果改变了，返回之前页面后刷新界面，没改变则不
    private MySingleOrderDeliveryStatusChangeListener mSingleOrderDeliveryStatusChangeListener;
    private RelativeLayout back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_detail);
        order_sn = this.getIntent().getStringExtra("order_sn");//从订单列表获取的订单编号
        status = this.getIntent().getStringExtra("status");
        userInfo =  IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        mSingleOrderDeliveryStatusChangeListener = new MySingleOrderDeliveryStatusChangeListener(this);

        initView();
        initListener();
        //initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onResume() {
        super.onResume();
        loadbuildingData();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_actionbar_up:
                //点击左上角的返回按钮
                finish();
                break;
            case R.id.btn_delivery_confirm://订单详情的签收按钮
                if(orderdetail.getS_key().equals("0")&&orderdetail.getPay_type().equals("货到付款")){
                    IOrder.getInstance().singalorderDeliveryStatusSign(orderdetail.getSn(), 1, orderdetail.getReal_money(), "",000,"","","",mSingleOrderDeliveryStatusChangeListener);
                }else{
                    Intent intent = getIntent();
                    intent.setClass(this,SelectPayTypeActivity.class);
                    intent.putExtra("orderdetail", (Serializable)orderdetail);
                    startActivity(intent);
                }
                break;
            case R.id.tv_receiver_phone:
                String phone = tv_receiver_phone.getText().toString().trim();
                Intent intent1 = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));// 用intent启动拨打电话(只显示手机号码不直接拨打电话)
                startActivity(intent1);
                break;
            case R.id.back:
                finish();
                break;
        }

    }

    /**
     * 如果店家物理返回按钮返回上一个页面， 对是否设置返回值进行判断设置
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isChaged){  // 订单状态发生改变，则把该订单编号返回给之前的界面
                Intent intent = getIntent();
                intent.putExtra("changedOrderSn",orderdetail.getSn());
                setResult(Define.ACTIVITY_CODE_ORDER_DETAI_CHANGE,intent);
            }
            isChaged = false;
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 初始化控件
     */
    public void initView(){
       // iv_action_back = (ImageView) this.findViewById(R.id.iv_actionbar_up);
        tv_actionbar_title = (TextView) this.findViewById(R.id.tv_actionbar_title);
        //tv_actionbar_deliveryName = (TextView) this.findViewById(R.id.tv_actionbar_deliveryName);

        tv_order_number = (TextView) this.findViewById(R.id.tv_order_number);
        tv_create_time = (TextView) this.findViewById(R.id.tv_create_time);
        tv_receiver_name = (TextView) this.findViewById(R.id.tv_receiver_name);
        tv_receiver_phone = (TextView) this.findViewById(R.id.tv_receiver_phone);
        tv_receiver_address = (TextView) this.findViewById(R.id.tv_receiver_address);
        tv_receiver_cpucbt = (TextView) this.findViewById(R.id.tv_receiver_cpucbt);
        tv_pay_type = (TextView) this.findViewById(R.id.tv_pay_type);
        tv_money = (TextView) this.findViewById(R.id.tv_money);
        tv_notes = (TextView) this.findViewById(R.id.tv_notes);
        tv_shimoney = (TextView) this.findViewById(R.id.tv_shimoney);


        productList = (LinearLayout) this.findViewById(R.id.list_products);
        tv_order_price = (TextView) this.findViewById(R.id.tv_order_price);
        tv_logistic_status = (TextView) this.findViewById(R.id.tv_logistic_status);
        tv_delivery_status = (TextView) this.findViewById(R.id.tv_delivery_status);
        btn_delivery_confirm = (Button) this.findViewById(R.id.btn_delivery_confirm);

        mloadCover = (LoadingCover) findViewById(R.id.layout_loading_cover);
        mloadCover.setOnLoadingCoverRefreshListener(this);
        listener = new OrderDetailListener(this);
        back = (RelativeLayout) findViewById(R.id.back);
        back.setOnClickListener(this);



    }

    /**
     * 初始化监听器
     */
    public void initListener(){
        //iv_action_back.setOnClickListener(this);
        tv_receiver_phone.setOnClickListener(this);
        btn_delivery_confirm.setOnClickListener(this);


    }

    /**
     * 获取订单详情
     */
    private void loadbuildingData() {
        IOrder.getInstance().getOrderDetail(order_sn, listener);
    }

    @Override
    public void onLoadingCoverRefresh() {
        loadbuildingData();
    }

    private static class OrderDetailListener extends GetQueryorderDetailListener{
        private OrderDetailActivity mOuter;
        public OrderDetailListener(OrderDetailActivity outer){
            this.mOuter = outer;
        }
        public void release(){
            new WeakReference<OrderDetailActivity>(mOuter);
        }

        @Override
        public void onResponseSuccess(OrderDetail orderdetailinfo) {
            if(mOuter == null){
                return;
            }
            mOuter.orderdetail = orderdetailinfo;
            mOuter.mloadCover.onRefreshSuccess();
            if (mOuter.orderdetail == null ){
                return ;
            }
            mOuter.tv_order_number.setText("编号："+mOuter.orderdetail.getSn());
            mOuter.tv_receiver_name.setText("收货人姓名："+mOuter.orderdetail.getReceiver_name());
            mOuter.tv_receiver_phone.setText("收货人电话："+mOuter.orderdetail.getReceiver_tel());
            mOuter.tv_receiver_address.setText("收货人地址："+mOuter.orderdetail.getReceiver_add());
            mOuter.tv_receiver_cpucbt.setText("提货方式："+mOuter.orderdetail.getCpucbt());
            if (mOuter.status.equals("1")){//已签收
                mOuter.tv_shimoney.setVisibility(View.VISIBLE);
                mOuter.tv_shimoney.setText("实收金额：" + mOuter.orderdetail.getReal_money());
                if (mOuter.orderdetail.getReceive_type().equals("1")){
                    mOuter.tv_pay_type.setText("收款方式："+"现金支付");
                }else if(mOuter.orderdetail.getReceive_type().equals("2")){
                    mOuter. tv_pay_type.setText("收款方式："+"POS机闪付");
                }else if(mOuter.orderdetail.getReceive_type().equals("3")){
                    mOuter. tv_pay_type.setText("收款方式："+"在线支付");
                }

            }else{
                mOuter.tv_shimoney.setVisibility(View.GONE);
                mOuter.tv_pay_type.setText("支付方式："+mOuter.orderdetail.getPay_type());
            }
            mOuter.tv_money.setText("应收金额：￥"+mOuter.orderdetail.getMoney());
            mOuter.tv_order_price.setText("￥"+mOuter.orderdetail.getMoney());
            tv_delivery_status.setText(mOuter.orderdetail.getOstatus());
            if (mOuter.orderdetail.getOstatus().equals("已签收")||mOuter.orderdetail.getOstatus().equals("用户撤单")||mOuter.orderdetail.getOstatus().equals("订单失效")){
                btn_delivery_confirm.setVisibility(View.GONE);
            }else{
                btn_delivery_confirm.setVisibility(View.VISIBLE);
            }
            mOuter.tv_notes.setText("备注："+mOuter.orderdetail.getNotes());
            mOuter.tv_create_time.setText(mOuter.orderdetail.getCreate_at());
            // 生成产品条目列表
            List<ProductInfo> products = mOuter.orderdetail.getProductInfos();
            mOuter.productList.removeAllViews();
            for (int j = 0 ; j < products.size() ; j++ ){
                ProductInfo productInfo = products.get(j);
                View productItemView = LayoutInflater.from(mOuter).inflate(R.layout.home_orders_products_item, null);
                TextView tv_product_name = (TextView) productItemView.findViewById(R.id.tv_product_name);
                TextView tv_total_price = (TextView)productItemView.findViewById(R.id.tv_total_price);
                tv_product_name.setText(productInfo.getProduct_name());
                // tv_product_name.setTextSize(Tools.sp2px(this, 13));
                tv_total_price.setText(productInfo.getProduct_num() + " × " + productInfo.getProduct_price());
                // tv_total_price.setTextSize(Tools.sp2px(this,13));
                // 如果是最后一个条目，则把分割线的宽度设置成和父窗体一样  （没效果啊 ！什么原因？）
                ImageView divider = (ImageView) productItemView.findViewById(R.id.vv_divider);
                if (j == products.size() - 1){
                    ((LinearLayout.LayoutParams)divider.getLayoutParams()).leftMargin = 0 ;
                }else{
                    ((LinearLayout.LayoutParams)divider.getLayoutParams()).leftMargin = Tools.dip2px(mOuter, 15);
                }
                mOuter.productList.addView(productItemView);
            }

        }

        @Override
        public void onNoMoreData() {
            if(mOuter == null){
                return;
            }
            mOuter.mloadCover.onRefreshFailed("暂无数据");
        }

        @Override
        public void onNoNetWork() {
            if(mOuter == null){
                return;
            }
            mOuter.mloadCover.onRefreshFailed();
            Toast.makeText(mOuter.getApplicationContext(), Define.MSG_NO_NETWORK, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onResponseFailed() {
            if(mOuter == null){
                return;
            }
            mOuter.mloadCover.onRefreshFailed();
        }

    }

    /**
     * 单订单业务签收回调接口
     */
    private class MySingleOrderDeliveryStatusChangeListener extends SingleOrderDeliveryStatusChangeListener {
        private OrderDetailActivity mOuter;

        public MySingleOrderDeliveryStatusChangeListener(OrderDetailActivity mOuter) {
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<OrderDetailActivity>(mOuter);
        }

        @Override
        public void onHasNotSignLogistic() {
            ToastUtils.showToast(mOuter.getApplicationContext(), "请先完成该订单的物流签收");

        }

        @Override
        public void onResponseSuccess() {
            btn_delivery_confirm.setVisibility(View.INVISIBLE);
            tv_delivery_status.setText("已签收");
            Intent broastIntent = new Intent(Define.ACTION_REFRESH_SHOPPING_CART);
            sendBroadcast(broastIntent);
            finish();
            ToastUtils.showToast(mOuter.getApplicationContext(), "业务签收成功");
        }

        @Override
        public void onNoNetWork() {
            ToastUtils.showToast(mOuter.getApplicationContext(),Define.MSG_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            ToastUtils.showToast(mOuter.getApplicationContext(),"业务签收失败");
        }
    }
}
